package com.dengxiujun.simpletomcat.request;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;

/**
 * <p></p>
 *
 * @author dengxiujun
 * @date 2021-04-26
 **/
public class HttpRequest {

    private String url;
    private String method;

    public HttpRequest(InputStream inputStream) throws IOException {
        byte[] bytes = new byte[1024];
        int readedLength = 0;
        String requestContent = "";
        if ((readedLength = inputStream.read(bytes)) > 0) {
            requestContent = new String(bytes, 0, readedLength, StandardCharsets.UTF_8);
            System.out.println("------------------------------------------ Request Content start ------------------------------------------");
            System.out.println(Thread.currentThread().getName() + ": " + requestContent);
            System.out.println("------------------------------------------ Request Content end   ------------------------------------------");
            System.out.println("\n\n");

            String requestContentFirstLine = requestContent.split("\n")[0];
            method = requestContentFirstLine.split("\\s")[0];
            url = requestContentFirstLine.split("\\s")[1];
        } else {
            throw new IllegalArgumentException("非法的http请求");
        }
    }

    public HttpRequest(SocketChannel socketChannel) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        if (socketChannel.read(buffer) > 0) {
            buffer.flip();
            CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
            CharBuffer charBuffer = decoder.decode(buffer.asReadOnlyBuffer());
            String requestContent = charBuffer.toString();
            System.out.println("------------------------------------------ Request Content start ------------------------------------------");
            System.out.println(Thread.currentThread().getName() + ": " + requestContent);
            System.out.println("------------------------------------------ Request Content end   ------------------------------------------");
            System.out.println("\n\n");

            String requestContentFirstLine = requestContent.split("\n")[0];
            method = requestContentFirstLine.split("\\s")[0];
            url = requestContentFirstLine.split("\\s")[1];
        } else {
            throw new IllegalArgumentException("非法的http请求");
        }
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

}
